<?php
/**
 * @ClassName: Order
 * @Description: TODO
 * @author: gydtrade
 * @Date: 2025-11-12 11:06
 * @Version: V1.0.0
 */

namespace app\api\controller;

use app\common\logic\CouponLogic;
use app\common\logic\GoodsLogic;
use app\common\logic\MemberLogic;
use app\common\logic\OrderLogic;
use app\common\model;

class Order extends Api
{
    /**
     * 订单列表
     * @return \think\response\Json
     */
    function orderList()
    {
        $type = input('type/d', 0);
        $orderType = input('orderType', 0);
        $skip = input('skip/d', 0);
        $limit = input('limit/d', 10);

        $logic = new OrderLogic($this->member_id);

        $where = [
            ['member_id', 'eq', $this->member_id],
        ];

        //订单状态，'全部', '待支付', '待发货', '待收货', '待评论', '已完成'
        switch ($type) {
            case 1:
                // 待支付
                $where[] = ['order_status', 'eq', 0];
                $where[] = ['pay_status', 'eq', 0];
                break;
            case 2:
                // 待发货
                $where[] = ['pay_status', 'eq', 1];
                $where[] = ['shipping_status', 'neq', 1];
                break;
            case 3:
                // 待收货
                $where[] = ['order_status', 'eq', 1];
                $where[] = ['shipping_status', 'eq', 1];
                break;
            case 4:
                /*// 待评论
                $where[] = ['order_status', 'eq', 2]; // 已经收货
                $where[] = ['order_status', 'neq', 1]; // 未评论
                break;*/
            case 5:
                // 已完成
                $where[] = ['order_status', 'eq', 4];
                break;
            default:
                // 全部
                break;
        }

        //订单类型，-1酒店订单，0联盟订单，1订水订单，2水架订单，3水桶订单，4水票订单，5门票订单，6排队免单订单，7饮水设备，8月结订单，9代理积分订单，10升级礼包，11用户积分订单
        switch ($orderType) {
            case '1':
                //订水订单（包含水票订单，月结订单）
                $where[] = ['order_type', 'in', [1, 4, 8]];
                break;
            case '2':
                //水架订单
                $where[] = ['order_type', 'eq', 2];
                break;
            case '3':
                //水桶订单
                $where[] = ['order_type', 'eq', 3];
                break;
            case '4':
                //排队免单订单
                $where[] = ['order_type', 'in', [6]];
                break;
            case '5':
                //饮水设备订单
                $where[] = ['order_type', 'in', [7]];
                break;
            default:
                //联盟订单（包含酒店订单、门票订单）
                $where[] = ['order_type', 'in', [0, 5, -1, 10, 11]];
                break;
        }

        $field = "id,order_sn,total_amount,order_amount,order_status,use_points,points_money,ext_points_money,ext_points,shipping_status,pay_status,pay_code,order_type,is_pickup_point,create_time,master_id";
        $list = model\ShopOrder::where($where)->order('id desc')
            ->limit($skip, $limit)
            ->field($field)
            ->select();

        foreach ($list as &$li) {
            $li = $logic->fieldProcessing($li);
        }

        $result = [
            'list' => $list,
            'is_more' => count($list) >= $limit
        ];

        return json(['code' => 1, 'data' => $result]);
    }

    /**
     * 订单详情
     * @return \think\response\Json
     */
    function detail()
    {
        $id = input('id', 0);

        $order = model\ShopOrder::get($id);
        if (!$order) {
            return json(['code' => 0, 'msg' => '订单不存在']);
        }

        $logic = new OrderLogic($this->member_id);
        $order = $logic->fieldProcessing($order);

        return json(['code' => 1, 'data' => $order]);
    }

    function action()
    {
        $action = input('action');
        $id = input('id/d');

        $where = [
            ['id' => $id],
            ['member_id' => $this->member_id]
        ];

        $data = model\ShopOrder::where($where)->find();
        if (!$data) {
            return json(['code' => 0, 'msg' => '订单不存在-' . $id, 'data' => []]);
        }

        $res = [];

        $logic = new OrderLogic($this->member_id);

        // 取消订单
        if ($action == 'cancel') {
            $res = $logic->cancelOrder($id, $this->member_id, '用户取消订单');
        } // 确认收货
        else if ($action == 'receive') {
            $res = $logic->confirmOrder($id, $this->member_id, '用户确认收货');
        } // 评论
        else if ($action == 'comment') {
            $res = $logic->commentOrder($id, $this->member_id, '用户发布评论');
        } // 退款申请
        else if ($action == 'return') {
            $res = $logic->returnOrder($id, $this->member_id, '用户申请退款');
        } // 删除订单
        else if ($action == 'del') {
            $res = $logic->delOrder($id, $this->member_id, '用户删除订单');
        } else {
            return json(['code' => 0, 'msg' => '未知操作-' . $action, 'data' => []]);
        }

        if ($res['code'] == 1) {
            $data = model\ShopOrder::where($where)->find();

            if ($data) {
                $logic = new OrderLogic($this->member_id);

                $data = $logic->fieldProcessing($data);

                return json(['code' => 1, 'msg' => 'ok', 'data' => $data]);
            }
        }
        return json($res);
    }

    function submitOrder()
    {
        $goods_id = input('goods_id', 0);
        $address_id = input('address_id', 0);
        $use_money = input('use_money', 0);
        $use_points = input('use_points', 0);
        $use_dot = input('use_dot', 0);
        $use_commission = input('use_commission', 0);
        $use_coupon_num = input('use_coupon_num', 0);
        $user_note = input('user_note', '');
        $coupon_id = input('coupon_id', 0);
        $goods_num = input('goods_num', 1);
        $skuid = input('skuid', 'none');
        $consignee = input('consignee', '');
        $mobile = input('mobile', '');
        $check_in_time = input('check_in_time', '');
        $check_out_time = input('check_out_time', '');

        $ticket_id = input('ticket_id', 0);
        $use_ticket = input('use_ticket', 0);//使用水票
        $use_monthly = input('use_monthly', 0);//使用月结

        $is_pickup_point = input('is_pickup_point', 0);
        $is_free_queuing = input('is_free_queuing', 0);
        $delivery_time = input('delivery_time', '');
        $user_role = input('user_role', 1);

        $member_id = $this->member_id;

        $spec_key = '';
        if ($skuid != 'none') {
            $sku = model\ShopGoodsSpecPrice::get($skuid);
            if (!$sku) {
                return json([
                    'code' => 0,
                    'msg' => '规格信息有误',
                ]);
            }
            $spec_key = $sku['spec_key'];
        }

        $logic = new OrderLogic($member_id, session_id());

        $data = [
            'address_id' => $address_id,
            'use_money' => $use_money,
            'use_points' => $use_points,
            'use_dot' => $use_dot,
            'use_commission' => $use_commission,
            'use_coupon_num' => $use_coupon_num,
            'user_note' => $user_note,
            'coupon_id' => $coupon_id,
            'goods_num' => $goods_num,
            'spec_key' => $spec_key,
            'consignee' => $consignee,
            'mobile' => $mobile,
            'check_in_time' => $check_in_time,
            'check_out_time' => $check_out_time,
            'use_ticket' => $use_ticket,
            'use_monthly' => $use_monthly,
            'ticket_id' => $ticket_id,
            'is_pickup_point' => $is_pickup_point,
            'is_free_queuing' => $is_free_queuing,
            'delivery_time' => $delivery_time,
            'user_role' => $user_role,
        ];
        $res = $logic->submit($goods_id, $data);

        if (!$res["code"]) {
            return json($res);
        }

        return json($res);
    }

    /**
     * 计算金额
     * @return \think\response\Json
     */
    public function summary()
    {
        // 1 引进依赖
        $logic = new OrderLogic($this->member_id, session_id());

        // 2 接收参数并验证
        $goods_id = input('goods_id', ''); // 商品id
        $address_id = input('address_id', '0');// 地址id
        $shipping_code = input('shipping_code', '');//物流方式
        $use_money = input('use_money', '0'); // 使用余额
        $use_points = input('use_points', '0'); // 使用积分
        $use_dot = input('use_dot', '0'); // 使用积分
        $use_commission = input('use_commission', '0'); // 使用佣金
        $use_coupon_num = input('use_coupon_num', '0'); // 使用优惠券
        $user_note = input('user_note', ''); // 用户备注
        $coupon_type = input('coupon_type', -1); // 优惠券类型，0平台券，1商家券
        $coupon_id = input('coupon_id', 0); // 优惠券ID
        $goods_num = input('goods_num', 1); // 商品数量
        $skuid = input('skuid', 'none');

        $is_pickup_point = input('is_pickup_point', 0);
        $is_free_queuing = input('is_free_queuing', 0);

        // 3 处理数据
        // 获取用户的地址
        $address = null;
        $address_list = model\MemberAddress::where(['member_id' => $this->member_id])->order('is_default desc')->select()->toArray();
        // 用户没有选地址，默认使用第一个
        if (!$address_id) {
            if (count($address_list)) {
                $address = $address_list[0];
                $address_id = $address['id'];
            }
        }

        // 获取物流方式
        $shipping_com = null;
        $shipping_list = model\ShippingCom::where(['enable' => 1])->select()->toArray();
        // 用户没有选物流，默认使用第一个
        if (!$shipping_code) {
            if (count($shipping_list)) {
                $shipping_com = $shipping_list[0];
                $shipping_code = $shipping_com['code'];
            }
        }

        $spec_key = '';
        if ($skuid != 'none') {
            $sku = model\ShopGoodsSpecPrice::get($skuid);
            if (!$sku) {
                return json([
                    'code' => 0,
                    'msg' => '规格信息有误',
                ]);
            }
            $spec_key = $sku['spec_key'];
        }

        $data = [
            'address_id' => $address_id, // 地址id
            'shipping_code' => $shipping_code, // 物流编码，计算物流费
            'use_dot' => $use_dot, // 使用使用积分(优享点):1使用，0不使用，使用后计算
            'user_note' => $user_note, // 用户备注
            'coupon_id' => $coupon_id,
            'goods_num' => $goods_num,
            'spec_key' => $spec_key,

            'use_money' => $use_money, // 使用金额: 不使用
            'use_points' => $use_points, // 使用积分(优享点)
            'use_commission' => $use_commission, // 使用收益:不使用
            'use_coupon_num' => $use_coupon_num, // 优惠券数量:不使用
            'coupon_type' => $coupon_type, // 优惠券类型，0平台券，1商家券
            'is_pickup_point' => $is_pickup_point,
            'is_free_queuing' => $is_free_queuing,
        ];

        $res = $logic->summary($goods_id, $data);

        // 组装数据返回
        $res['shipping_list'] = $shipping_list;

        return json($res);
    }

    /**
     * 获取支付方式
     * @return \think\response\Json
     */
    public function getPayWayList()
    {
        $type = input('type', 0);

        //月结权限
        $month_settle = (new MemberLogic())->getMonthSettle($this->member_id);

        $list = [];
        $list[] = [
            'value' => 0,
            'name' => '水票',
        ];
        $list[] = [
            'value' => 1,
            'name' => '在线支付',
        ];

        if ($month_settle['settle_status'] && $type == 0) {
            $list[] = [
                'value' => 2,
                'name' => '月结',
            ];
        }

        return json(['code' => 1, 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 用户最后一次订水订单
     * @return \think\response\Json
     */
    public function getLastBuyOrder()
    {
        $member_id = $this->member_id;
        $store_id = input('store_id', 0);

        $orderLogic = new OrderLogic($member_id);

        $order = $orderLogic->getLastBuyOrder($store_id, $member_id);

        return json(['code' => 1, 'msg' => '获取成功', 'data' => $order]);
    }

}